package org.imlinker.login;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;

/**
 * 登录线程.
 */
public class Login extends Thread {

	public Login() {

		// 初始化登录界面。
		windowManager = new WindowManager(this);
	}

	public XMPPConnection getConnection() {
		return connection;
	}

	public void run() {

		boolean loginSuccess = false;

		// 大循环，直到登录成功跳出。
		while (!loginSuccess) {

			// 等待设置account，
			final int sleepSeconds = 100;
			while (fullAccount == null) {
				try {
					Thread.sleep(sleepSeconds);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			// 开始连接服务器
			// 提示信息
			windowManager.setStatusByBundle("Login.conntect");

			String host = fullAccount.getHost();
			int port = Integer.parseInt(fullAccount.getPort());
			String domain = fullAccount.getDomain();
			ConnectionConfiguration config = new ConnectionConfiguration(host,
					port, domain);

			connection = new XMPPConnection(config);
			try {
				connection.connect();
			} catch (XMPPException e) {
				e.printStackTrace();
			}

			// 开始登录
			if (connection.isConnected()) {
				// 连接服务器成功，开始登录
				windowManager.setStatusByBundle("Login.logining");

				String username = fullAccount.getUser();
				String password = fullAccount.getPassword();

				try {
					connection.login(username, password);
				} catch (XMPPException e) {
				}

				if (connection.isAuthenticated()) {
					// 帐号登录成功
					loginSuccess = true;

					windowManager.setStatusByBundle("Login.initialing");
				} else {

					// 帐号登录失败
					windowManager.setStatusByBundle("Login.loginfailed");

					fullAccount = null;
				}

			} else {
				// 连接服务器失败的情况

				fullAccount = null;

				windowManager.setStatusByBundle("Login.connectfailed");
			}

		}

		windowManager.closeLoginWindow();
	}

	public void setAccount(final Account account) {
		fullAccount = Accounts.fillAccount(account);
	}

	private Account fullAccount;

	private WindowManager windowManager;

	private XMPPConnection connection;

}
